package com.sinoyd.itszyw.Dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoyd.itszyw.Activity.BaseActivity;
import com.sinoyd.itszyw.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import static com.sinoyd.itszyw.MyApplication.VERSION_DATA;

/**
 * @createBy : Sinoyd 大饼洲
 * @description :
 * @projectName : ITYW
 * @creationDate: 2017-04-01 14:56
 */
public class DownloadDialog extends Dialog{

    private static ProgressBar bar;
    private static TextView tvDetail;
    private static DownloadListener downloadListener;

    public DownloadDialog(Context context) {
        super(context);
    }

    public DownloadDialog(Context context, int theme) {
        super(context, R.style.dialog_no_dimenabled);
    }

    public static class Builder {
        private Context context;

        public Builder(Context context) {
            this.context = context;
        }

        public DownloadDialog create() {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final DownloadDialog dialog = new DownloadDialog(context,
                    R.style.dialog_no_dimenabled);
            View layout = inflater.inflate(R.layout.dialog_download, null);
            dialog.setCanceledOnTouchOutside(true);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.addContentView(layout, new LinearLayout.LayoutParams(
                    context.getResources().getDimensionPixelSize(R.dimen.x260), LinearLayout.LayoutParams.WRAP_CONTENT));
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads().detectDiskWrites().detectNetwork()
                    .penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                    .penaltyLog().penaltyDeath().build());
            bar = (ProgressBar) layout.findViewById(R.id.down_pb);
            tvDetail = (TextView) layout.findViewById(R.id.down_tv);
            downLoadFile();
            dialog.setContentView(layout);
            dialog.setDownloadListener((BaseActivity) context);
            return dialog;
        }

        private void downLoadFile() {
            String fileName = "ITYW.apk";
            String savePathString = Environment.getExternalStorageDirectory()
                    + "/DownLoadApp/" + fileName;
            final File file = new File(savePathString);
            if (!file.exists()) {
                // 需下载的文件不存在
                // 执行下载
                // 判断文件夹是否存在
                String savePAth = Environment.getExternalStorageDirectory()
                        + "/DownLoadApp";
                File file1 = new File(savePAth);
                if (!file1.exists()) {
                    file1.mkdir();
                }
            }
            try {

                Thread thread = new Thread() {
                    public void run() {
                        try {
//							MyApplication.VERSION_DATA.VerUrl="http://218.4.71.45:8000/V02ZJG.Air/ReferenceMaterial/Common/EnvironmentZJG_Beta_V13_20150730.apk";
                            URL url = new URL(VERSION_DATA.VerUrl);
                            URLConnection connection = url.openConnection();
                            InputStream inputStream = connection.getInputStream();
                            int max = connection.getContentLength();
                            int downSize = 1;
                            int len = -1;
                            byte[] buffer = new byte[1024];
                            FileOutputStream outputStream = new FileOutputStream(
                                    file);
                            while ((len = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, len);
                                outputStream.flush();
                                downSize += len;
                                int x = downSize * 100 / max;
                                bar.setProgress(x);
                                Message message2 = new Message();
                                message2.what = 2;
                                message2.obj = downSize*100/max+"%";
                                handler.sendMessage(message2);
                            }
                            Message message2 = new Message();
                            message2.what = 1;
                            handler.sendMessage(message2);
                            inputStream.close();
                            outputStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        Toast.makeText(context,"下载完成,准备安装软件....",Toast.LENGTH_SHORT).show();
                        downloadListener.endDownload(Environment
                                .getExternalStorageDirectory()
                                + "/DownLoadApp/ITYW.apk");
                        break;
                    case 2:
                        tvDetail.setText(msg.obj.toString());
                        break;
                    default:
                        break;
                }
            }
        };

    }

    public void setDownloadListener(DownloadListener downloadListener) {
        this.downloadListener = downloadListener;
    }

    public static interface DownloadListener {
        /***
         * 开始下载
         */
        public void startDownload();

        /***
         * 下载完成
         *
         * @param filePath
         */
        public void endDownload(String filePath);
    }

}
